package com.chcit.mobile.mvp.hight.fragment;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.hight.adapter.HightCostAdapter;
import com.chcit.mobile.mvp.hight.contract.HightCostContract;
import com.chcit.mobile.mvp.hight.presenter.HightCostPresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.mvp.hight.di.component.DaggerHightCostReceiveComponent;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;
import com.xuexiang.xui.widget.toast.XToast;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HightCostReceiveFragment extends ScanFragment<HightCostPresenter> implements HightCostContract.View {

    @BindView(R.id.et_hcr_productName)
    ValidatorEditText etProductName;
    @BindView(R.id.img_scan_package)
    AppCompatImageView imgPakcageNo;
    @BindView(R.id.lv_hcr_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.bt_hcr_ok)
    Button btOk;
    @BindView(R.id.et_hcr_patientCode)
    ValidatorEditText etPatientCode;
    @BindView(R.id.img_scan_patientCode)
    AppCompatImageView imgPatientCode;
    @BindView(R.id.et_hcr_patientName)
    ValidatorEditText etPatientName;
    @BindView(R.id.img_scan_patientName)
    AppCompatImageView imgPatientName;
    private String userCode;
    private HightCostAdapter mAdapter;
    private List<PackageBean> packageBeanList = new ArrayList<>();
    private static final int PACKAGE_NO_CODE = 222;
    private static final int PATIENT_CODE_CODE = 223;
    private static final int PATIENT_NAME_CODE = 224;
    protected Intent captureActivityIntent = null;
    public static HightCostReceiveFragment newInstance() {
        HightCostReceiveFragment fragment = new HightCostReceiveFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHightCostReceiveComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_hight_cost_receive, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        init();
        initRecyclerView();
        initEvent();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(etPatientName.isFocused()){
            etPatientName.setText(barcodeData);
            hideSoftInput();
        }else if(etPatientCode.isFocused()){
            etPatientCode.setText(barcodeData);
            hideSoftInput();
        }else{
            etProductName.setText(barcodeData);
            doQueryData();

        }
    }

    private void initEvent() {
        etProductName.addTextChangedListener(textWatcher);
        etProductName.setOnEditorActionListener((v,actionId,event)->{
            if (actionId == EditorInfo.IME_ACTION_SEARCH&&v.getText().length()>0) {//EditorInfo.IME_ACTION_SEARCH、EditorInfo.IME_ACTION_SEND等分别对应EditText的imeOptions属性
                //TODO回车键按下时要执行的操作
                doQueryData();
                return true;
            }
            return false;
        });
        etPatientCode.addTextChangedListener(textWatcher);
        etPatientName.addTextChangedListener(textWatcher);
        imgPakcageNo.setOnClickListener(v->{
            initZxing(PACKAGE_NO_CODE);
        });
        imgPatientCode.setOnClickListener(v->{
            initZxing(PATIENT_CODE_CODE);
        });
        imgPatientName.setOnClickListener(v->{
            initZxing(PATIENT_NAME_CODE);
        });
    }

    private void init() {

        userCode = _mActivity.getIntent().getStringExtra("userCode");
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter = new HightCostAdapter(packageBeanList);
        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        mAdapter.enableSwipeItem();
        mAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        mAdapter.enableDragItem(mItemTouchHelper);
        mAdapter.setOnItemDragListener(listener);
        mRecyclerView.setAdapter(mAdapter);
    }


    @OnClick({ R.id.bt_hcr_ok})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.bt_hcr_ok) {// {warehouseId:1212,bpartnerId:121212,userCode:"23235gg",patientCode:"asas",patientName:"张三",packageNo:["wewe","wewec"]}
            if (!(packageBeanList.size() > 0)) {
                return;
            }
            JSONArray packages = new JSONArray();
            for (PackageBean p : packageBeanList) {
                packages.add(p.getPackageNo());
            }
            //    warehouseId:1000214
            //    patientCode:54545
            //    patientName:545454
            //    packageNo:["(00)090000004000002502"]
            JSONObject requestParam = new JSONObject();
            requestParam.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
            requestParam.put("patientCode", etPatientCode.getText());
            requestParam.put("patientName", etPatientName.getText());
            requestParam.put("packageNo", packages);
            mPresenter.borrowUserByPackage(requestParam, list -> {
                ArmsUtils.snackbarTextWithLong("操作成功！");
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                etProductName.setText("");
                etPatientCode.setText("");
                etPatientName.setText("");
            });
        }
    }

    private void doQueryData() {
        PackageBean packageBean = new PackageBean(etProductName.getText().toString());
        int position = packageBeanList.indexOf(packageBean);
        if (position >= 0) {
            new MaterialDialog.Builder(mContext)
                    .title("提示")
                    .content("该条码已被扫过，是否删除？")
                    .negativeText("删除")
                    .positiveText("取消")
                    .onNegative((dialog, which) -> {
                        mAdapter.remove(position);
                    })
                    .build()
                    .show();
            return;
        }
        JSONObject params = new JSONObject();
        params.put("packageNo",etProductName.getText().toString());
        // params.put("packageStatus","S");//在库
        params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        mPresenter.getPakcageInfo(params, list->{
            mAdapter.addData(list.get(0));
        });
    }

    private int mEditTextHaveInputCount = 0;
    private TextWatcher textWatcher = new TextWatcher() {


        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                  btOk.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 3;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                  btOk.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    protected void initZxing(int code){

        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        if(captureActivityIntent==null){
            captureActivityIntent = new Intent(mContext, CaptureActivity.class);
            ZxingConfig config = new ZxingConfig();
            config.setPlayBeep(true);//是否播放扫描声音 默认为true
            config.setShake(true);//是否震动  默认为true
            config.setDecodeBarCode(true);//是否扫描条形码 默认为true
            config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
            config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
            config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
            config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            captureActivityIntent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        }
        startActivityForResult(captureActivityIntent, code);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (resultCode == RESULT_OK&& data != null) {
            String content = data.getStringExtra(Constant.CODED_CONTENT);
            switch (requestCode){
                case PACKAGE_NO_CODE:
                   etProductName.setText(content);
                    doQueryData();
                    break;
                case PATIENT_CODE_CODE:
                    etPatientCode.setText(content);
                    break;
                case PATIENT_NAME_CODE:
                    etPatientName.setText(content);
                    break;
            }

        }
    }
}
